//
//  YSSplashAdCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/19.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  启动+广告页

#import "YSSplashAdCtrl.h"
#import "YSNewFeaturesCtrl.h"
#import "CustomTabBarCtrl.h"
#import "YSHomeDataTool.h"
#import <AVFoundation/AVFoundation.h>

static const float PLAYER_VOLUME = 0.0;

@interface YSSplashAdCtrl ()

@property (weak, nonatomic) IBOutlet UIImageView *bgImgView;
@property (assign, nonatomic) UInt64 startTime;;
@property (assign, nonatomic) UInt64 endTime;;
@property (strong, nonatomic) YSSetupInfoRes *result;
@property (weak, nonatomic) IBOutlet UIButton *jumpBtn;
@property (strong, nonatomic) NSTimer *countDownTimer;
@property (strong, nonatomic) NSString *adImage;

@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) UIView *playerView;

@property (assign, nonatomic) BOOL isClickJump;
@end

@implementation YSSplashAdCtrl

-(BOOL)shouldStatusBarLightContent{
    return YES;
}

-(BOOL)shouldHideStatusBar{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor blackColor]];
    _startTime = [[NSDate date] timeIntervalSince1970]*1000;
    // 1.背景图片
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    NSLog(@"height=%f",height);
    
    self.playerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    [self.view insertSubview:self.playerView belowSubview:self.bgImgView];
    
    
    if(height==480){// 4s 4
        self.bgImgView.image = [UIImage imageNamed:@"splash_image"];
    }else if(height==568){// 5s 5
        self.bgImgView.image = [UIImage imageNamed:@"splash_image_568"];
    }else if(height==667){// 6
        self.bgImgView.image = [UIImage imageNamed:@"splash_image_667"];
    }else if(height==736){// 6 plus
        self.bgImgView.image = [UIImage imageNamed:@"splash_image_736"];
    }
    /*
    //定时器两秒后执行
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(timeCount) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:_countDownTimer forMode:NSDefaultRunLoopMode];
     
    //启动页面显示3秒
    [NSThread sleepForTimeInterval:3.0];
     */
    [_jumpBtn setHidden:YES];
    [self setupInfo];
    [self createVideoPlayer];
}

-(void)setupInfo{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [YSHomeDataTool getSetupInfo:^(YSSetupInfoRes *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if(result.isSucc){
                    _result = result;
                    // 归档存储appinfo
                    [NSKeyedArchiver archiveRootObject:result toFile:YSAppInfoFilePath];
                    
                    //如果是第一次安装不显示广告页
                    if([[DefaultsHelper stringForKey:kAppVersion] isEqualToString:[SystemUtil getAppVersion]]){
                        YSAdvert *ad =  result.banner;
                        if(ad){
                            _endTime = [[NSDate date] timeIntervalSince1970]*1000;
                            _adImage = ad.advertImg;
                        }
                    }
                }
            });
        } failure:^(NSError *error) {
            _endTime = [[NSDate date] timeIntervalSince1970]*1000;
        }];
    });
}

-(void)tapAd:(UITapGestureRecognizer *)sender{
    _isClickJump = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    UIWindow *window = theApp.window;
    window.rootViewController = [[CustomTabBarCtrl alloc]init];
    [window makeKeyAndVisible];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kToOtherPageNortif object:_result.banner.advertUrl];
}

-(void)toNextCtrl{
    NSString *appVersion = [DefaultsHelper stringForKey:kAppVersion];
    if (ISBLANK(appVersion)|| ![appVersion isEqualToString:[SystemUtil getAppVersion]]) {
        UIWindow *window = theApp.window;
        window.rootViewController = [[YSNewFeaturesCtrl alloc]init];
        [window makeKeyAndVisible];
    }else{
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
        UIWindow *window = theApp.window;
        window.rootViewController = [[CustomTabBarCtrl alloc]init];
        
        [window makeKeyAndVisible];
    }
}

- (IBAction)tapJump:(id)sender {
    _isClickJump = YES;
    [self toNextCtrl];
}

-(void)timeCount{
    if(!ISBLANK(_adImage)){//判断广告是否显示
        [self showAdPage:_adImage];
         //开始倒计时，两秒后跳过ad页面
        __weak typeof (self) weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [NSThread sleepForTimeInterval:2.0];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(!_isClickJump){
                    [weakSelf toNextCtrl];
                }
            });
        });
    }else{
        [self toNextCtrl];
    }
}

-(void)showAdPage:(NSString *)adImage{
    [_jumpBtn setHidden:NO];
    [self.bgImgView setImageURLStr:adImage];
    self.bgImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAd:)];
    [self.bgImgView addGestureRecognizer:tap];
}

- (void)createVideoPlayer {
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player.volume = PLAYER_VOLUME;
    
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    playerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:playerLayer];
    
    [self.player play];
    
  
    [self.player.currentItem addObserver:self forKeyPath:AVPlayerItemDidPlayToEndTimeNotification options:NSKeyValueObservingOptionNew context:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

#pragma mark - observer of player
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"observeValueForKeyPath");
    //处理不影响系统播放其他音乐
    [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
}

// 视频播放结束
- (void)moviePlayDidEnd:(NSNotification*)notification{
    [self timeCount];
}

- (void)dealloc {
     [self.player.currentItem removeObserver:self forKeyPath:AVPlayerItemDidPlayToEndTimeNotification context:nil];
    [self.player.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
